package com.sdy.dcsb.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.dcsb.biz.model.EsbInboundParam;
import com.sdy.dcsb.biz.model.swagger.EsbInboundParamPageData;
import com.sdy.dcsb.biz.service.EsbInboundParamService;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author Snaky
 */
@Slf4j
@Controller
@RequestMapping("/EsbInboundParam")
@Api(tags = "服务目录参数配置相关接口")
public class EsbInboundParamController extends BaseController {

    @Autowired
    private EsbInboundParamService esbInboundParamService;

    @GetMapping("/pageData")
    @ResponseBody
    @ApiOperation(value = "参数配置页面数据", response = EsbInboundParamPageData.class)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "serviceId", value = "服务id，必传"),
            @ApiImplicitParam(dataType = "Integer", name = "paramMode", value = "参数模式(1 入参  2 出参)，不传时获取所有参数"),
            @ApiImplicitParam(dataType = "Integer", name = "current", value = "当前页，默认为1"),
            @ApiImplicitParam(dataType = "Integer", name = "size", value = "分页大小，默认为5")
    })
    public Response pageData(Integer serviceId, Integer paramMode, Integer current, Integer size) throws Exception{
        Assert.isNull(serviceId, "服务id为空");

        if(current == null){
            current = 1;
        }
        if(size == null){
            size = 5;
        }
        QueryWrapper<EsbInboundParam> wrapper = new QueryWrapper<>();
        wrapper.eq("service_id", serviceId)
                .orderByAsc("param_mode","order_num");
        if(paramMode != null){
            wrapper.eq("param_mode", paramMode);
        }

        IPage<EsbInboundParam> page = esbInboundParamService.page(new Page<>(current, size, 0), wrapper);
        return Response.success(page);
    }

    @PostMapping(value = "/save", produces = "application/json;charset=UTF-8")
    @ResponseBody
    @ApiOperation("新增/修改 接口服务参数信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "参数id，修改时必传"),
            @ApiImplicitParam(dataType = "Integer", name = "serviceId", value = "服务id，必传"),
            @ApiImplicitParam(dataType = "Integer", name = "paramMode", value = "参数模式(1 入参  2 出参)，必传"),
            @ApiImplicitParam(dataType = "Integer", name = "responseDataType", value = "返回数据类型(1 json格式、2 xml格式)，出参时必传"),
            @ApiImplicitParam(dataType = "Integer", name = "paramFormat", value = "入参格式(1 地址栏参数、2 head参数、3 json格式、4 form-data参数、5 form-urlencoded参数)，入参时必传"),
            @ApiImplicitParam(dataType = "Integer", name = "paramType", value = "参数类型(1 一般参数 、 2 常量参数)，入参时必传"),
            @ApiImplicitParam(dataType = "String", name = "paramKey", value = "参数名，可为空"),
            @ApiImplicitParam(dataType = "String", name = "paramName", value = "参数含义，可为空"),
            @ApiImplicitParam(dataType = "String", name = "paramValue", value = "参数值，参数类型为常量参数时必传"),
            @ApiImplicitParam(dataType = "Integer", name = "nodeType", value = "节点类型(1 int、2 string、3 boolean、4 jsonObject、5 jsonArray)，必传"),
            @ApiImplicitParam(dataType = "Integer", name = "parentOrderNum", value = "父节点序号，可为空")
    })
    public Response save(HttpServletRequest request, @RequestBody JSONObject json) throws Exception{
        Integer serviceId = json.getInteger("serviceId");
        Integer id = json.getInteger("id");
        Integer paramMode = json.getInteger("paramMode");
        Integer responseDataType = json.getInteger("responseDataType");
        Integer paramFormat = json.getInteger("paramFormat");
        Integer paramType = json.getInteger("paramType");
        String paramKey = json.getString("paramKey");
        String paramName = json.getString("paramName");
        String paramValue = json.getString("paramValue");
        Integer nodeType = json.getInteger("nodeType");
        Integer parentOrderNum = json.getInteger("parentOrderNum");

        Assert.isNull(serviceId, "服务id为空");
        Assert.isNull(paramMode, "参数模式为空");
        if(paramMode == 2){
            Assert.isNull(responseDataType, "返回数据类型为空");
        } else {
            Assert.isNull(paramFormat, "参数格式为空");
            Assert.isNull(paramType, "参数类型为空");
            if(paramType == 2){
                Assert.isNull(paramValue, "参数值为空");
            }
            if(paramFormat == 3){
                Assert.isNull(nodeType, "节点类型为空");
            }
            List<Integer> format = esbInboundParamService.getParamFormat(serviceId);
            // 3 json格式、4 form-data参数、5 form-urlencoded参数
            if(format != null && format.size() > 0 && paramFormat > 2){
                if(!format.contains(paramFormat)){
                    return Response.error("参数格式冲突");
                }
            }
        }

        EsbInboundParam inboundParam = new EsbInboundParam();
        inboundParam.setId(id)
                .setServiceId(serviceId)
                .setParamMode(paramMode)
                .setResponseDataType(responseDataType)
                .setParamFormat(paramFormat)
                .setParamType(paramType)
                .setParamKey(paramKey)
                .setParamName(paramName)
                .setParamValue(paramValue)
                .setNodeType(nodeType)
                .setParentOrderNum(parentOrderNum);

        boolean flag;
        if(id == null){
            // 新增参数
            Integer maxOrderNum = esbInboundParamService.getMaxOrderNum(serviceId, paramMode);
            if(maxOrderNum == null){
                maxOrderNum = 0;
            }
            maxOrderNum++;
            inboundParam.setOrderNum(maxOrderNum)
                    .setCreateDate(new Date());
            flag = esbInboundParamService.save(inboundParam);
        } else {
            // 修改参数
            inboundParam.setOrderNum(esbInboundParamService.getById(id).getOrderNum())
                    .setUpdateDate(new Date());
            flag = esbInboundParamService.updateById(inboundParam);
        }
        if(flag){
            return Response.success();
        }
        return Response.error("保存错误");

    }

    @PostMapping(value = "/delete", produces = "application/json;charset=UTF-8")
    @ResponseBody
    @ApiOperation("删除接口服务参数信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "参数id，必传"),
            @ApiImplicitParam(dataType = "Integer", name = "serviceId", value = "服务编码，必传"),
            @ApiImplicitParam(dataType = "Integer", name = "paramMode", value = "参数模式(1 入参  2 出参)，必传")
    })
    public Response delete(HttpServletRequest request, @RequestBody JSONObject json) throws Exception{
        Integer serviceId = json.getInteger("serviceId");
        Integer id = json.getInteger("id");
        Integer paramMode = json.getInteger("paramMode");

        Assert.isNull(serviceId, "服务id为空");
        Assert.isNull(id, "参数id为空");
        Assert.isNull(paramMode, "参数模式为空");

        // 查询是否存在对应参数
        QueryWrapper<EsbInboundParam> wrapper = new QueryWrapper<>();
        wrapper.eq("service_id", serviceId)
                .eq("param_mode", paramMode)
                .eq("id", id);

        EsbInboundParam inboundParam = esbInboundParamService.getOne(wrapper);

        if (inboundParam == null) {
            return Response.error("参数不存在，删除失败");
        }
        // 查询当前参数有无子节点
        QueryWrapper<EsbInboundParam> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("service_id",serviceId)
                .eq("param_mode",paramMode)
                .eq("parent_order_num",inboundParam.getOrderNum());
        int count = esbInboundParamService.count(wrapper2);
        if(count > 0){
            return Response.error("存在子节点参数，无法直接删除");
        }

        // 删除参数
        boolean flag = esbInboundParamService.remove(wrapper);
        if(flag){
            return Response.success();
        }
        return Response.error("删除错误");
    }


}
